package com.openweixin.sheknows.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.openweixin.sheknows.domain.User;




/**
 * 描述：Controller基类，定义一些需要用到的常量
 * 注意事项：无
 * @author 刘思作
 * @version 1.0.0 2014-04-01
 * @since 1.0.0
 */
public class BaseController {
	public static final String SUCCESS = "{\"success\":true}";
	public static final String FAIL = "{\"success\":false}";
	public static final String SESSION_USER = "USER";
	public static final Short USER_MEMBER = 0;
	public static final Short USER_EXPERT = 1;
	
	protected static HttpServletRequest getRequest(){
		return ((ServletRequestAttributes)
				RequestContextHolder.getRequestAttributes()).getRequest();
	}
	public static User getLoginUser(){
		return (User)getRequest().getSession().getAttribute(SESSION_USER);
	}
	
	protected void setSessionAttribute(String key,Object o){
		getRequest().getSession().setAttribute(key, o);
	}
	/**
	 * 获得远程连接的IP
	 */
	public static String getRequestRemoteAddress() {
		HttpServletRequest request = getRequest();
		String ip = request.getHeader("X-Real-IP");
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip =  request.getHeader("x-forwarded-for");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		int split = StringUtils.indexOf(ip, ",");
		if (split>0) {
			ip = ip.substring(0,split);
		}
		return ip;
	}

}
